package com.supermap.mouseListeners;

import com.supermap.Helper;
import com.supermap.consts.AttrConsts;
import com.supermap.data.*;
import com.supermap.dialogs.*;
import com.supermap.mapping.*;
import com.supermap.ui.LayersTree;
import com.supermap.ui.NodeDataType;
import com.supermap.ui.TreeNodeData;
import com.supermap.panes.LayerPropertiesSettingPane;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class LayersTreeMouseListener implements MouseListener {
    private final LayersTree layersTree;
    private final JSplitPane dataPane;
    private final JSplitPane settingPane;

    public LayersTreeMouseListener(LayersTree layersTree, JSplitPane dataPane, JSplitPane settingPane) {
        this.layersTree = layersTree;
        this.dataPane = dataPane;
        this.settingPane = settingPane;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        Object source = e.getSource();
        if (!(source instanceof LayersTree)) {
            return;
        }
        LayersTree layersTree = (LayersTree) source;
        JPopupMenu popupMenu = layersTree.getComponentPopupMenu();
        if (popupMenu != null) {
            popupMenu.removeAll();
            popupMenu.setVisible(false);
        }

        switch (e.getButton()) {
            // 鼠标左键
            case MouseEvent.BUTTON1:
                break;
            // 鼠标中键
            case MouseEvent.BUTTON2:
                break;
            // 鼠标右键
            case MouseEvent.BUTTON3:
                if (popupMenu == null) {
                    popupMenu = new JPopupMenu();
                    layersTree.setComponentPopupMenu(popupMenu);
                    popupMenu.setLocation(e.getLocationOnScreen());
                } else {
                    popupMenu.removeAll();
                    popupMenu.setVisible(false);
                }

                TreeNodeData selectedTreeNode = Helper.getSelectedTreeNode(layersTree);
                if (selectedTreeNode == null) {
                    return;
                }

                NodeDataType nodeType = selectedTreeNode.getType();
                // 图层右键菜单
                if (nodeType == NodeDataType.LAYER) {
                    Object layerData = selectedTreeNode.getData();
                    if (layerData instanceof Layer) {
                        initLayerContextMenu(popupMenu, (Layer) layerData);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    /**
     * 初始化图层鼠标右键菜单
     *
     * @param popupMenu 鼠标右键菜单对象
     * @param layer     当前选中图层
     */
    private void initLayerContextMenu(JPopupMenu popupMenu, Layer layer) {
        JMenuItem canVisibleItem = new JMenuItem("可显示");
        canVisibleItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            layer.setVisible(!layer.isVisible());
        });
        popupMenu.add(canVisibleItem);

        JMenuItem canSelectableItem = new JMenuItem("可选择");
        canSelectableItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            layer.setSelectable(!layer.isSelectable());
        });
        popupMenu.add(canSelectableItem);

        JMenuItem canEditItem = new JMenuItem("可编辑");
        canEditItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            layer.setEditable(!layer.isEditable());
        });
        popupMenu.add(canEditItem);

        JMenuItem canItem = new JMenuItem("可捕捉");
        canItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            layer.setSnapable(!layer.isSnapable());
        });
        popupMenu.add(canItem);

        JMenuItem viewEntireItem = new JMenuItem("全幅显示本图层");
        viewEntireItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            Rectangle2D layerBounds = layer.getBounds();
            layer.getMap().setViewBounds(layerBounds);
            layer.getMap().refresh();
        });
        popupMenu.add(viewEntireItem);

        JMenuItem viewDataItem = new JMenuItem("关联浏览属性数据");
        viewDataItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            Dataset dataset = layer.getDataset();
            if (!(dataset instanceof DatasetVector)) {
                return;
            }

            DatasetVector datasetVector = (DatasetVector) dataset;
            QueryParameter queryParameter = new QueryParameter();
            queryParameter.setCursorType(CursorType.STATIC);
            queryParameter.setHasGeometry(true);
            queryParameter.setResultFields(new String[]{AttrConsts.WILDCARD});
            queryParameter.setAttributeFilter(AttrConsts.EMPTY);
            queryParameter.setOrderBy(new String[]{});
            queryParameter.setGroupBy(new String[]{});
            Recordset recordset = datasetVector.query(queryParameter);

            JTable dataTable = new JTable();
            dataTable.getSelectionModel().addListSelectionListener(e1 -> {
                Selection selection = layer.getSelection();
                selection.clear();
                int[] selectedIndices = ((DefaultListSelectionModel) e1.getSource()).getSelectedIndices();
                for (int i = 0; i < selectedIndices.length; i++) {
                    selectedIndices[i] += 1;
                }
                selection.addRange(selectedIndices);
                GeoStyle selectionStyle = selection.getStyle();
                selectionStyle.setFillBackColor(Color.RED);
                selectionStyle.setFillForeColor(Color.RED);
                selectionStyle.setLineColor(Color.RED);
                selection.setStyleOptions(StyleOptions.FILLBACKCOLOR, true);
                selection.setDefaultStyleEnabled(false);
                Recordset selRecordset = selection.toRecordset();
                Rectangle2D bounds = selRecordset.getBounds();
                if (bounds.getLeft() == bounds.getRight()) {
                    Point2D center = bounds.getCenter();
                    bounds = new Rectangle2D(center.x - 0.5, center.y + 0.5, center.x + 0.5, center.y - 0.5);
                }
                Map map = layer.getMap();
                map.setViewBounds(bounds);
                map.refresh();
            });

            Helper.loadTabular(recordset, dataTable);
            JScrollPane dataScrollPane = new JScrollPane(dataTable);
            JTabbedPane dataTabPane = new JTabbedPane();
            dataTabPane.addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    switch (e.getButton()) {
                        case MouseEvent.BUTTON1:
                            break;
                        case MouseEvent.BUTTON2:
                            break;
                        case MouseEvent.BUTTON3:
                            JPopupMenu dataPopupMenu = new JPopupMenu();
                            JMenuItem closeItem = new JMenuItem("关闭");
                            closeItem.addActionListener(e1 -> {
                                dataPopupMenu.setVisible(false);
                                dataTabPane.remove(dataScrollPane);
                                if (dataTabPane.getTabCount() == 0) {
                                    dataPane.setBottomComponent(null);
                                }
                                Selection selection = layer.getSelection();
                                selection.clear();
                            });
                            dataPopupMenu.add(closeItem);
                            dataPopupMenu.setLocation(e.getLocationOnScreen());
                            dataPopupMenu.setVisible(true);
                            break;
                    }
                }

                @Override
                public void mousePressed(MouseEvent e) {

                }

                @Override
                public void mouseReleased(MouseEvent e) {

                }

                @Override
                public void mouseEntered(MouseEvent e) {

                }

                @Override
                public void mouseExited(MouseEvent e) {

                }
            });
            dataTabPane.addTab(layer.getCaption() + "关联属性表", dataScrollPane);
            dataPane.setBottomComponent(dataTabPane);
            dataPane.setDividerLocation((int) (dataPane.getHeight() * 0.7));
        });
        popupMenu.add(viewDataItem);

        JMenuItem removeLayerItem = new JMenuItem("移除");
        removeLayerItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            layer.getMap().getLayers().remove(layer);
            layersTree.reload();
        });
        popupMenu.add(removeLayerItem);

        JMenuItem renameLayerItem = new JMenuItem("重命名");
        renameLayerItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            Frame frame = (Frame) layersTree.getRootPane().getParent();
            InputNameDialog renameLayerDialog = new InputNameDialog(frame, "重命名图层", true);
            renameLayerDialog.setVisible(true);
            String newLayerName = renameLayerDialog.getInputText();
            renameLayerDialog.dispose();
            if (newLayerName.equals(AttrConsts.EMPTY)) {
                return;
            }

            layer.setCaption(newLayerName);
            layersTree.reload();
        });
        popupMenu.add(renameLayerItem);

        JMenu createThemeUniqueLayerMenu = new JMenu("制作专题图");
        popupMenu.add(createThemeUniqueLayerMenu);
        JMenuItem themeUniqueItem = new JMenuItem("单值专题图");
        themeUniqueItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            Frame frame = (Frame) layersTree.getRootPane().getParent();
            ThemeUniqueDialog themeLayerDialog = new ThemeUniqueDialog(frame, "新建单值专题图", true, (DatasetVector) layer.getDataset());
            themeLayerDialog.setVisible(true);
            ThemeUnique themeUnique = themeLayerDialog.getThemeUnique();
            themeLayerDialog.dispose();

            if (themeUnique == null) {
                return;
            }

            addThemeLayer(layer, themeUnique);
        });
        createThemeUniqueLayerMenu.add(themeUniqueItem);

        JMenuItem themeLabelItem = new JMenuItem("统一标签专题图");
        themeLabelItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            Frame frame = (Frame) layersTree.getRootPane().getParent();
            DatasetVector datasetVector = (DatasetVector) layer.getDataset();
            JoinItems joinItems = null;
            QueryParameter queryParameter = layer.getDisplayFilter();
            if (queryParameter != null) {
                joinItems = queryParameter.getJoinItems();
            }
            ThemeLabelDialog themeLabelDialog = new ThemeLabelDialog(frame, "新建统一标签专题图", true, datasetVector, joinItems);
            themeLabelDialog.setVisible(true);
            ThemeLabel themeLabel = themeLabelDialog.getThemeLabel();
            themeLabelDialog.dispose();

            if (themeLabel == null) {
                return;
            }

            addThemeLayer(layer, themeLabel);
        });
        createThemeUniqueLayerMenu.add(themeLabelItem);

        JMenuItem themeGraphItem = new JMenuItem("统计专题图");
        themeGraphItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            Frame frame = (Frame) layersTree.getRootPane().getParent();
            ThemeGraphDialog themeGraphDialog = new ThemeGraphDialog(frame, "新建统计专题图", true, (DatasetVector) layer.getDataset());
            themeGraphDialog.setVisible(true);
            ThemeGraph themeGraph = themeGraphDialog.getThemeGraph();
            themeGraphDialog.dispose();

            if (themeGraph == null) {
                return;
            }

            addThemeLayer(layer, themeGraph);
        });
        createThemeUniqueLayerMenu.add(themeGraphItem);

        JMenuItem layerPropertiesItem = new JMenuItem("图层属性");
        layerPropertiesItem.addActionListener(e -> {
            popupMenu.setVisible(false);
            LayerPropertiesSettingPane layerPropertiesSettingPane = new LayerPropertiesSettingPane("图层属性", layer);
            settingPane.setRightComponent(new JScrollPane(layerPropertiesSettingPane));
            settingPane.setResizeWeight(1);
        });
        popupMenu.add(layerPropertiesItem);

        popupMenu.setVisible(true);
    }

    private void addThemeLayer(Layer layer, Theme theme) {
        Dataset dataset;
        QueryParameter queryParameter = layer.getDisplayFilter();
        if (queryParameter != null && queryParameter.getJoinItems() != null && queryParameter.getJoinItems().getCount() > 0) {
            dataset = layer.getDataset().getDatasource().getDatasets().get(queryParameter.getJoinItems().get(0).getForeignTable());
        } else {
            dataset = layer.getDataset();
        }
        Map map = layer.getMap();
        map.getLayers().add(dataset, theme, true);
        Workspace workspace = map.getWorkspace();
        String mapName = map.getName();
        Maps maps = workspace.getMaps();
        if (maps.indexOf(mapName) != -1) {
            maps.setMapXML(mapName, map.toXML(), workspace.getVersion());
        }
        map.refresh();
        layersTree.reload();
    }
}
